<?php
use Illuminate\Support\Facades\Response as FacadesResponse;
use \Illuminate\Database\Eloquent\ModelNotFoundException;

/**
 * @author hongyang
 */
class QuestionController extends BaseController {
	
    protected $layout = 'layouts.master';

	/**
	 * 获取问题，如果出错了，会返回合适的Response
	 * 
	 * @param integer $id
	 */
	protected function getQuestion($id) {
		try {
			$post = Post::findOrFail($id);
		} catch(ModelNotFoundException $e) {
			return $this->makeView(
				'errors.404',
				'没有找到符合要求的纪录。',
				404
			);
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'咨询律师失败，请稍后再试。',
				503
			);
		}
		return $post;
	}
	
	/**
	 * 显示问题内容
	 */
	public function view($id) {
		$post = $this->getQuestion($id);

		if (!is_a($post, 'Post')) {
		    return $post;
		}
		
		$post->load('postExtra', 'comments');

		$postArr = $post->toArray();

		foreach($postArr['comments'] as &$comments) {
			$creatorId = $comments['creator_id'];
			$creator = User::find($creatorId);
			if($creator==null) $creator=User::find(2);//默认人
			$creator->load('lawyer');
			$owner = $creator->toArray();
			$comments['creator_id'] = $owner['id'];
			$comments['difference_date'] = UtilsHelper::differenceFormat($comments['created_at']);
			$comments['creator_avatar'] = UtilsHelper::getImage($owner['avatar'], "img/dfimg.png");
			$comments['creator_name'] = $owner['realname'];
			$comments['creator_company_name'] = $owner['lawyer']['company_name'];
			$comments['creator_practice_period'] = UtilsHelper::getPracticePeriodStr($owner['lawyer']['practice_period']);
			$comments['creator_average_evaluate_score'] = number_format($owner['lawyer']['average_evaluate_score'], 1);
			$comments['creator_case_count'] = $owner['lawyer']['case_count'];

			// $comments['owner'] = $creator->toArray();
			// $comments['owner']['avatar'] = UtilsHelper::getImage($comments['owner']['avatar'], "img/dfimg.png");
			$comments['from_creator'] = (bool) ($postArr['creator_id'] == $comments['creator_id']);
			// 登录用户是否已经关注了律师
			$comments['is_following'] = (bool) Follow::isFollowing($comments['creator_id']);
			$comments['is_liked'] = Comment::isLiked($comments['id']);
			$comments['like_count'] = Comment::likeCount($comments['id']);
		}
		if (Auth::user() ) {
			$postArr['is_collect'] = Collect::where('item_id', $id)->where('collect_type', Collect::TYPE_ARTICLE)->where('creator_id', Auth::user()->id)->first();
		} else {
			$postArr['is_collect'] = false;
		}
		if (Auth::user() && $post->canReply(Auth::user()->id, $postArr['status'])) {
			$postArr['can_reply'] = true;
		} else {
			$postArr['can_reply'] = false;
		}
		if (Auth::user()) {
			$postArr['confirm'] = ($postArr['creator_id'] == Auth::user()->id && $postArr['status'] == Post::STATUS_WAIT_FOR_EVALUATION);
		}
		if(Auth::check())
		{
			$postArr['is_collect'] = Collect::collected_post($post);
		}
        
        $postCreator = null;
		if ($postArr['creator_id']) {
    		$postCreator = User::find($postArr['creator_id']);
    	}

    	if (!$postCreator) {
		    $postArr['creator_avatar'] = UtilsHelper::getImage("", "img/dfimg.png");
		    $postArr['creator_realname'] = "匿名用户";
    	} else {
    		$postCreatorArr = $postCreator->toArray();
    		$postArr['creator_avatar'] = UtilsHelper::getImage($postCreatorArr['avatar'], "img/dfimg.png");
    		$postArr['creator_realname'] = $postCreator['nikname'];
    	}
    	
        $postArr['post_category_str'] = UtilsHelper::getWorkScopeName($postArr['post_category']);
        $postArr['difference_date'] = UtilsHelper::differenceFormat($postArr['created_at']);

		try {
			// 增加浏览次数
			$postExtra = $post->postExtra()->first();
			if (!$postExtra) {
		        $postExtra = new PostExtra();
		        $postExtra->views_count = 0;
		        $postExtra->comments_count = 0;
		        $postExtra->likes_count = 0;
		        $postExtra->collects_count = 0;
			    $postExtra->last_comment_user_id = 0;
			    $post->postExtra()->save($postExtra);
			}

			$postExtra->increment('views_count');
			$postExtra->touch();
			$postExtra->save();
		} catch(Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'请稍后再试。',
				503
			);
		}
		return $this->makeView('question.public.view', $postArr);
	}
	
	/**
	 * 显示问题列表页面
	 */
	public function listContainer() {
		$workScopeList = UtilsHelper::workScope();
		$publishedDates = UtilsHelper::getPublishedDates();
		$cities = UtilsHelper::getCities();
		$listOrders = self::getListOrders();
		$this->layout = View::make('layouts.master');
		$this->layout->content = View::make ( 
			'question.list', 
			array(
				'workscopes' => $workScopeList,
				'publishedDates' => $publishedDates,
				'cities' => $cities,
				'listOrders' => $listOrders
			)
		);
	}

	protected function getCreatedAt($dateStr)
	{
		$time = null;
		switch($dateStr) {
			case '1day':
				$time = strtotime("-1 day");
				break;
			case '3days':
				$time = strtotime("-3 days");
				break;
			case '1week':
				$time = strtotime("-1 week");
				break;
			case '2weeks':
				$time = strtotime("-2 weeks");
				break;
			case '1month':
				$time = strtotime("-1 month");
				break;
		}
		if ($time) {
			return date('Y-m-d H:i:s', $time);
		} else {
			return null;
		}
	}

	/**
	 * 罗列所有问题，包括其它人问的问题。不显示问题人，但是显示解答问题的律师。
	 * 
	 * - make sure about the default values
	 *   - q 搜索关键字
	 *   - city_id 城市
	 *   - cat_id 行业领域
	 *   - published 发布日期
	 */
	public function listQuestions() {
		$input = Input::all();
        $cat_id = Input::get('cat_id', 0);
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $published = Input::get('published', null);
        $created_at = $this->getCreatedAt($published);
        // $city_id = $this->getCityId($input);
        $city_id = Input::get('city_id', 0);
        $q = Input::get('q', '');
		$offset = ($page-1) * $rows_per_page;
		$order = Input::get('order', 'latest');
		$orderby = 'created_at';
		$direction = 'DESC';
		if ($order == 'chronological') {
		    $direction = 'ASC';
		}
		
		$rules = array (
			'cat_id' => 'numeric|min:1',
			'page' => 'numeric|min:1',
			'rows_per_page' => 'numeric|min:1',
			'city_id' => 'numeric|min:1',
			// 'published' => 'date'
		);
		$messages = array(
			'cat_id.numeric' => 'cat_id需要是数字',
			'cat_id.min' => 'cat_id不能少于1',
			'page.numeric' => 'page需要是数字',
			'rows_per_page.numeric' => 'rows_per_page需要是数字',
			'city_id.numeric' => 'city_id需要是数字'
		);
		$validator = Validator::make ( $input, $rules, $messages );
			if ($validator->fails()) {
				// the given data did not pass validation
	            return $this->makeView(
	                'errors.400', 
	                $validator->errors(),
	                400
	            );
			}
		
		try {
			$posts = Post::getQuestions(
				$cat_id, 
				$city_id, 
				$q, 
				$offset, 
				$rows_per_page,
				$created_at,
			    $orderby,
			    $direction,
				null,
				[Post::STATUS_COMPLETE, Post::STATUS_WAIT_FOR_EVALUATION]
			);

			//$postsArr = $posts->toArray();
			foreach($posts as &$postArr) {
				$postArr->post_category = $postArr->getPostCatKey();
				$postArr->lawyer = $postArr->getLawyerName();
			}
			$postsArr = $posts->toArray();
			if ($order == 'most_replies') {
			     usort($postsArr, array($this, 'sortArray'));
			}
			
			return $this->makeView(
				'question.list', 
				$postsArr
			);
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'咨询律师失败，请稍后再试。',
				503
			);
		}
	}
	
	public function sortArray($a, $b) {
	    return count($a['comments']) < count($b['comments']);
	}
	
	/**
	 * 从不同的地方获取city_id
	 * - 提交的参数
	 * - session
	 * - 淘宝的地域信息服务
	 * 
	 * @param array $input 用户提交的数据
	 */
	private function getCityId($input) {
		if( isset($input['city_id']) && $input['city_id']) {
			$city_id = $input['city_id'];
			Session::put('city_id', $city_id);
		} else if(Session::get('city_id')) {
			$city_id = Session::get('city_id');
		} else {
        	$area = UtilsHelper::get_client_city_info_by_taobao_service();
			$city_id = $area['city_id'];
		}
		return $city_id;
	}
	
	/**
     * 获取相似的咨询
	 */
	public function similar($id) {
		$question = $this->getQuestion($id);
		if (!is_a($question, 'Post')) {
			return $question;
		} else {
			$question = $question->toArray();
		}
		
        $page = Input::get('page', 0);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = $page * $rows_per_page;
		
		// 找类似的问题
		// - 同一个类别的问题
		// - 热门问题
		$similarQuestions = Post::join('post_extras', 'posts.id', '=', 'post_extras.post_id')
			->select('posts.id', 'post_category', 'title', 'content', 'posts.created_at', 'views_count', 'likes_count')
			->whereType(Post::TYPE_QUESTION)
			->wherePostCategory($question['post_category'])
			->where('posts.id', '!=', $id)
			->take($rows_per_page)
			->skip($offset)
			->orderBy('posts.created_at', 'DESC')
			->get();

		try {
			return $this->makeView(
				'question.list',
				$similarQuestions->toArray()
			);
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'咨询律师失败，请稍后再试。',
				503
			);
		}
	}

	protected function getListOrders()
	{
		return array(
			'latest' => '最新',
			'most_replies' => '回复最多',
			'chronological' => '按时间排序'
		);
	}
	
	public function evaluateTags()
	{
	    $tags = [];
	    foreach(Evaluate::getAvailableEvaluateTags() as $key => $value) {
	        $tags[] = [
	            'key' => $key, 
	            'value' => $value
	        ];
	    }
	    
		return $this->makeView(
			'evaluate.tags',
			$tags
		);
	}
}
